<?php

namespace app\admin\controller\qingdong\report;
use addons\qingdong\model\File;
use addons\qingdong\model\Remind;
use addons\qingdong\model\Staff;
use app\admin\controller\qingdong\Base;
use app\common\controller\Backend;
use addons\qingdong\model\Form;
use addons\qingdong\model\Daily as DailyModel;
use addons\qingdong\model\Message;
use addons\qingdong\model\Comment;
use think\DB;
use think\Exception;
use function EasyWeChat\Kernel\Support\get_client_ip;
/**
 * 工作报告
 */
class Daily extends Base {
    /**
     * @var \addons\qingdong\model\Daily
     */
    protected $model = null;
    public function _initialize() {
        parent::_initialize();
        $this->model = new DailyModel();
    }

    /**
     * 工作报告
     */
    public function index() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',0);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            switch($type){
                case 1:
                    $staff = Staff::info();
                    $wheres['create_staff_id'] =  $staff->id;
                    break;
                case 2:
                    $wheres['create_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['create_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $whereT=[];
            $staff_id=input('staff_id');
            if($staff_id){
                $whereT['create_staff_id']=$staff_id;
            }
            $staff_id=$this->_staff->id;
            $list   = $this->model->where($where)->where($whereT)->where($wheres)
                ->where(function ($query) use ($staff_id,$wheres){
                    $query->where($wheres)
                        ->whereOr('','exp', Db::raw('FIND_IN_SET(' . $staff_id. ',reminds_id)'));
                })
                ->order($sort, $order)->with(['staff'])->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $types = $params['type'];
                    switch($types){
                        case '日报':
                            $typeinfo ='daily';
                            break;
                        case '周报':
                            $typeinfo ='weekly';
                            break;
                        case '月报':
                            $typeinfo ='monthly';
                            break;
                        case '季报':
                            $typeinfo ='quarterly';
                            break;
                        case '年报':
                            $typeinfo ='yearly';
                            break;
                        default:
                            $typeinfo ='daily';
                            break;
                    }
                    $form = Form::getDataValue($typeinfo);
                    foreach($form as $k=>$v){
                        if($v['component'] == 'uploadImage' || $v['component'] == 'uploadFile'){
                            if(key_exists($v['id'],$params)){
                                if($params[$v['id']]){
                                    $filearr = explode(',',$params[$v['id']]);
                                    $files ='';
                                    if($filearr){
                                        foreach($filearr as $ks=>$vs){
                                            $files = File::where(array('file_path|id'=>$vs))->order('id desc')->value('id').','.$files;
                                        }
                                        $params[$v['id']] = rtrim($files,',');
                                    }
                                }
                            }
                        }elseif($v['component'] == 'select'){
                            if(isset($v['config']['multiple']) &&  $v['config']['multiple'] == true){
                                if(key_exists($v['id'],$params)){
                                    if($params[$v['id']]){
                                        $params[$v['id']] = implode(',',$params[$v['id']]);
                                    }
                                }
                            }
                        }
                    }
                    $params['create_staff_id'] = $this->_staff->id;
                    $result = $this->model::createDaily($params);

                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $type=input('type','daily');

        $data=[
            'daily'=>'日报',
            'weekly'=>'周报',
            'monthly'=>'月报',
            'quarterly'=>'季报',
            'yearly'=>'年报',
        ];
        $this->assign('staff', Staff::where([])->column('name', 'id'));
        $this->assign('form_data', Form::getDataValue($type));
        $this->assign('type', $data[$type]??'日');

        $remind=Remind::where(['type'=>Remind::DAILY_TYPE])->find();
        $staff_ids=$remind['staff_ids']??'';
        $this->assign('staff_ids', $staff_ids);
        return $this->view->fetch();
    }

    /**
     * 工作报告详情
     */
    public function detail($ids = null) {
        $row = $this->model->with(['staff'])->where([
            'id'       => $ids
        ])->find();
        $row=$row->toArray();
        $row=array_merge($row,$row['other']);
        switch($row['type']){
            case '日报':
                $type = 'daily';
                break;
            case '周报':
                $type ='weekly';
                break;
            case '月报':
                $type = 'monthly';
                break;
            case '季报':
                $type = 'quarterly';
                break;
            case '年报':
                $type = 'yearly';
                break;
            default:
                $type = 'daily';
                break;
        }

        $form = Form::getDataValue($type,$row);
        foreach($form as $k=>$v){
            if($v['component'] == 'uploadImage' || $v['component'] == 'uploadFile'){
                if(key_exists($v['id'],$row)){
                    if(isset($row[$v['id']]) && $row[$v['id']]){
                        $whereT['id'] = array('in',$row[$v['id']]);
                        $fileinfo = File::where($whereT)->field('id,name,file_path')->select();
                        if($fileinfo){
                            $row[$v['id']] = $fileinfo;
                        }
                    }
                }
            }
        }
        $this->assign('form_data',$form );
        $this->assign('row', $row);
        $this->assignconfig("idinfo", ['id' => $ids]);

        return $this->view->fetch();
    }
    /**
     * 添加评论
     */
    public function comment($ids=null) {
        if ($this->request->isPost()) {
            $content = input('content');
            if (empty($content)) {
                $this->error('评论内容不能为空');
            }
            $data = [
                'relation_type' => Comment::DAILY_TYPE,
                'relation_id' => $ids,
                'staff_id' => $this->_staff->id,
                'content' => $content,
                'status' => 1,
                'ip' => get_client_ip(),
            ];
            $commentModel = new Comment();
            $commentModel->save($data);

            $daily = DailyModel::get($ids);

            Message::addMessage(Message::COMMENT_TYPE, $ids, $daily->create_staff_id, $this->_staff->id);

            $this->success('评论成功');
        }
        return $this->view->fetch();
    }
    /**
     * 评论
     */
    public function comment_list() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $relation_id = input('relation_id','');
            $wheres['relation_id'] = $relation_id;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list   = Comment::where($where)->where($wheres)->with(['staff','record'])->order($sort, $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }
}